package com.matt.service.impl;

import com.matt.domain.roleJob.RoleJob;
import com.matt.domain.roleJob.RoleJobFinish;
import com.matt.commons.exception.BusinessException;

import com.matt.foundation.model.ErrorCode;
import com.matt.foundation.model.MemVerificationCache;
import com.matt.foundation.utils.DateUtil;
import com.matt.foundation.vo.roleJob.RoleJobListVo;
import com.matt.repository.RoleJob.RoleJobFinishRepository;
import com.matt.repository.RoleJob.RoleJobRepository;
import com.matt.service.RoleJobService;
import com.matt.service.remoteCall.SsoCallService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.transaction.Transactional;
import java.util.*;
import java.util.stream.Collectors;


@Service
@Slf4j
public class RoleJobServiceImpl implements RoleJobService {

    @Autowired
    private RoleJobRepository roleJobRepository;

    @Autowired
    private RoleJobFinishRepository roleJobFinishRepository;


    @Autowired
    private SsoCallService ssoCallService;

    @Value("${spring.redis.host}")
    private String host;

    @Autowired
    private MemVerificationCache cache;


    @Override
    public Page<RoleJobListVo> getJobListByRoleCode(String staffId,String roleCode, Integer pageNum, Integer pageSize) {
        Date now = new Date();
        boolean isFirday = DateUtil.isFriday(now);
        boolean isEndOfMonth =  DateUtil.isLastDayOfMonth(now);
        boolean isDecember =  DateUtil.isDecember();
        boolean isLastWeekOfMonth =  DateUtil.getLastWeekOfMonth();
        Specification<RoleJob> specification = new Specification<RoleJob>() {
            @Override
            public Predicate toPredicate(Root<RoleJob> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();

                if (StringUtils.isNotBlank(roleCode))
                    predicates.add(criteriaBuilder.and(criteriaBuilder.equal(root.get("roleCode"), roleCode)));
                    predicates.add(criteriaBuilder.and(criteriaBuilder.equal(root.get("deleted"), false)));
                    if(!isFirday){ //周五出现
                        predicates.add(criteriaBuilder.and(criteriaBuilder.notEqual(root.get("remark"), "friday")));

                    }
                    if(!isEndOfMonth){//月末最后一天
                        predicates.add(criteriaBuilder.and(criteriaBuilder.notEqual(root.get("remark"), "endofmonth" )));
                    }

                    if(!isDecember){//12月
                        predicates.add(criteriaBuilder.and(criteriaBuilder.notEqual(root.get("remark"), "december" )));
                    }
                    if(!isLastWeekOfMonth){//是否月底的前7天
                        predicates.add(criteriaBuilder.and(criteriaBuilder.notEqual(root.get("remark"), "lastweekofmonth" )));
                    }


                query.where(predicates.toArray(new Predicate[predicates.size()]));
                query.orderBy(criteriaBuilder.asc(root.get("orderNum")));
                return query.getRestriction();
            }
        };
        Page<RoleJob> roleJobPage = roleJobRepository.findAll(specification, PageRequest.of(pageNum, pageSize));
        List<RoleJob> list = Lists.newArrayList();
        roleJobPage.getContent().stream().forEach(o -> {
            list.add(o);
        });



         String today = DateUtil.getToday();
         String month = DateUtil.getMonth();
         String year =  DateUtil.getYear();
        List<RoleJobFinish> finishList = roleJobFinishRepository.selectFinishJob(staffId, roleCode, today);
        System.out.println("---finishList size==="+finishList.size());
        List<String> finishJobIdList = Lists.newArrayList();
        for(RoleJobFinish finish : finishList){
            finishJobIdList.add(finish.getJobId());
        }

        List<RoleJobListVo> RoleJobList = Lists.newArrayList();

      for(RoleJob job :list){
            String jobId =job.getId();
            boolean isFinish = false;
            if(finishJobIdList.contains(jobId)){
                    isFinish = true ;
            }

            RoleJobListVo vo = RoleJobListVo.of(jobId,job.getTitle(),job.getContent(),job.getImgUrl(),job.getExpValue(),job.getActionUrl(),job.getRoleCode(),isFinish);
            RoleJobList.add(vo);
        }

       //排序 已完成的排后面
       List<RoleJobListVo> returnList = RoleJobList.stream().sorted(new Comparator<RoleJobListVo>() {
            @Override
            public int compare(RoleJobListVo o1, RoleJobListVo o2) {
                boolean flag1 = o1.isFinish();
                boolean flag2 = o2.isFinish();
                //两个值进行位运算,值不同为1,为true,参与运算
                //值相同为0,为false,不参与运算
                if (flag2 ^ flag1) {
                    return flag2 ? -1 : 1;
                } else {
                    return 0;
                }
            }
        }).collect(Collectors.toList());

        if(isLastWeekOfMonth){
            List<RoleJobFinish> monthFinishList = roleJobFinishRepository.selectMonthFinishJob(staffId, roleCode, month);//查询本月是否已经完成过 月底任务
            for(RoleJobFinish finish :monthFinishList){
                String jobId = finish.getJobId();
                Iterator<RoleJobListVo> iterator = returnList.iterator();
                while(iterator.hasNext()){
                    RoleJobListVo vo = iterator.next();
                    if(vo.getJobId().equals(jobId))
                        iterator.remove();   //注意这个地方
                }
            /*    for(RoleJobListVo vo : returnList){
                    if(vo.getJobId().equals(jobId)){
                        returnList.remove(vo);
                    }
                }*/
            }

        }

        if(isDecember){
            List<RoleJobFinish> yearFinishList = roleJobFinishRepository.selectYearFinishJob(staffId, roleCode, year);//查询今年是否完成过12月任务
        }

        return new PageImpl(returnList, PageRequest.of(pageNum, pageSize), roleJobPage.getTotalElements());
    }

    @Transactional
    @Override
    public Map<String, Object> jobFinish(String staffId,String roleCode,String jobId) {
        Map<String, Object> result = new HashMap<>();
        if (StringUtils.isNotBlank(jobId) && StringUtils.isNotBlank(staffId) && StringUtils.isNotBlank(roleCode)){
            RoleJob job = roleJobRepository.getOne(jobId);
            if(null != job){
                Date now = new Date();
                System.out.println("job titile:" + job.getTitle());
                int expValue = job.getExpValue();


                String today = DateUtil.getToday();
                RoleJobFinish hasFinish = roleJobFinishRepository.selectFinishByJobIdAndFinishTime(staffId,roleCode,today,jobId);
                if(null == hasFinish){
                    RoleJobFinish finish = RoleJobFinish.of(now, staffId, expValue, jobId, roleCode);
                    roleJobFinishRepository.save(finish);

//                    StaffExp staffExp = staffExpRepository.findByStaffIdAndRoleCode(staffId, roleCode);
//                    if(null == staffExp){
//                        staffExp = StaffExp.of(staffId, expValue,roleCode);
//                    }else{
//                        int  hasExp = staffExp.getExpValue();
//                        int  totalExp = hasExp + expValue ;
//                        staffExp.setExpValue(totalExp);
//                    }
//
//                    staffExpRepository.save(staffExp);
//
//                    //下面查询当前用户当前角色的 等级和经验信息
//                    int level = 1;
//                    int levelUpExp = 100 ;
//                    int currentExp = 0;
//                    StaffExp hasStaffExp =  staffExpRepository.findByStaffIdAndRoleCode(staffId, roleCode);
//                    if(null != hasStaffExp){
//                        int exp = hasStaffExp.getExpValue() ;
//                        if(exp < 100){
//                            currentExp = exp;
//                        }else{
//                            LevelExp levelExp =  levelExpRepository.selectLevelByExp(exp);
//                            currentExp= exp - levelExp.getLevelTotalExp() ;
//                            level = Integer.parseInt(levelExp.getId())+1 ;
//                            levelUpExp = levelExpRepository.getOne(String.valueOf(level)).getLevelUpExp();
//                        }
//                    }
//                    result.put("level", level);
//                    result.put("currentExp", currentExp);
//                    result.put("levelUpExp", levelUpExp);


                }else{
                    throw new BusinessException(ErrorCode.ID_IS_ERROR, "请勿重复完成任务");
                }




            }else{
                throw new BusinessException(ErrorCode.ID_IS_ERROR, "jobId不存在");
            }
        }else{
            throw new BusinessException(ErrorCode.PARAM_CAN_NOT_BLANK, "必填项不能为空");
        }

      return result ;

    }
}
